<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="广告编号" prop="adId">
        <el-input
          v-model="queryParams.adId"
          placeholder="请输入广告表的广告编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 数据记录日期 -->
      <el-form-item label="数据日期" prop="recordDate">
        <el-date-picker clearable
                        v-model="queryParams.recordDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择数据记录日期"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 搜索和重置按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:performance:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:performance:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:performance:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:performance:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格展示广告数据 -->
    <el-table v-loading="loading" :data="performanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="performanceId"/>
      <el-table-column label="广告名称" align="center" prop="adName"/>
      <el-table-column label="广告点击量" align="center" prop="clickRate"/>
      <el-table-column label="广告转化率" align="center" prop="conversionRate"/>
      <el-table-column label="数据记录日期" align="center" prop="recordDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:performance:edit']"-->
<!--          >修改-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:performance:remove']"-->
<!--          >删除-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 表单内容 -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <br><br>
    <!-- ECharts 饼图容器 -->
    <div id="click-rate-chart" style="width: 100%; height: 400px;"></div>
    <br>
    <div id="pie-chart" style="width: 100%; height: 400px;"></div>

  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  listPerformance,
  getPerformance,
  delPerformance,
  addPerformance,
  updatePerformance
} from '@/api/system/performance'

export default {
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      performanceList: [],
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adId: null,
        clickRate: null,
        conversionRate: null,
        recordDate: null
      },
      form: {},
      rules: {
        adId: [
          { required: true, message: '广告表的广告编号不能为空', trigger: 'blur' }
        ],
        clickRate: [
          { required: true, message: '广告点击率不能为空', trigger: 'blur' }
        ],
        conversionRate: [
          { required: true, message: '广告转化率不能为空', trigger: 'blur' }
        ],
        recordDate: [
          { required: true, message: '数据记录日期不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询广告数据列表 */
    getList() {
      this.loading = true
      listPerformance(this.queryParams).then(response => {
        this.performanceList = response.rows
        this.total = response.total
        this.loading = false
        this.initECharts() // 在数据获取后初始化 ECharts
        this.initPieChart() // 在数据获取后初始化 ECharts 饼图
      })
    },
    /** 初始化 ECharts 图表 */
    initECharts() {
      const chartDom = document.getElementById('click-rate-chart')
      const myChart = echarts.init(chartDom)

      // 获取所有广告名称
      const adNames = [...new Set(this.performanceList.map(item => item.adName))]

      // 颜色数组与广告名称一一对应
      const colors = [
        ['#80FFA5', '#00DDFF'],  // 清新的绿色到蓝色渐变
        ['#37A2FF', '#FF0087'],  // 明亮的蓝色到粉红色渐变
        ['#6fa0f9', '#8871f3'],  // 柔和的蓝色到紫色渐变
        ['#FFBF00', '#FF6F00'],  // 明亮的黄色到橙色渐变
        ['#FF8C00', '#FF4500']   // 热烈的橙色到红色渐变
      ]

      // 为每个广告名称创建一个系列
      const series = adNames.map((adName, index) => ({
        name: adName,
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 0
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: colors[index % colors.length][0] // 使用数组中的颜色
            },
            {
              offset: 1,
              color: colors[index % colors.length][1]
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: this.performanceList
          .filter(item => item.adName === adName)
          .sort((a, b) => new Date(a.recordDate) - new Date(b.recordDate)) // 确保数据按日期排序
          .map(item => item.clickRate) // Y 轴数据为点击量
      }))

      const option = {
        color: colors.flat(), // 展平颜色数组用于图例颜色
        title: {
          text: '广告点击量趋势图'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: adNames
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [...new Set(this.performanceList.map(item => item.recordDate))] // X 轴数据为记录日期
        },
        yAxis: {
          type: 'value'
        },
        series: series
      }

      myChart.setOption(option)
    },
    /** 初始化 ECharts 饼图 */
    initPieChart() {
      const chartDom = document.getElementById('pie-chart')
      const myChart = echarts.init(chartDom)

      // 计算每个广告的百分比
      const totalClicks = this.performanceList.reduce((sum, item) => sum + item.clickRate, 0)
      const pieData = this.performanceList.map(item => ({
        value: item.clickRate,
        name: item.adName,
        percent: ((item.clickRate / totalClicks) * 100).toFixed(2) + '%'
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {d}%'
        },
        title: {
          text: '广告转化率趋势图'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '广告来源',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {d}%',
              position: 'outside'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: pieData
          }
        ]
      }

      myChart.setOption(option)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        adId: null,
        clickRate: null,
        conversionRate: null,
        recordDate: null
      }
      this.getList()
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.title = '新增广告数据'
      this.open = true
      this.form = {}
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = '修改广告数据'
      this.open = true
      this.form = { ...row }
    },
    /** 提交表单 */
    submitForm() {
      if (this.form.performanceId) {
        updatePerformance(this.form).then(() => {
          this.$message.success('修改成功')
          this.getList()
          this.open = false
        })
      } else {
        addPerformance(this.form).then(() => {
          this.$message.success('新增成功')
          this.getList()
          this.open = false
        })
      }
    },
    /** 取消操作 */
    cancel() {
      this.open = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('确认删除该广告数据?', '提示', {
        type: 'warning'
      }).then(() => {
        delPerformance(row.performanceId).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('确认导出数据?', '提示', {
        type: 'warning'
      }).then(() => {
        // 执行导出操作
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.fixed-width {
  width: 160px;
}
.small-padding {
  padding: 0 10px;
}
</style>
